<!--renshuai-->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="厂商编号" prop="pkId">
        <el-input
          v-model="queryParams.pkId"
          placeholder="请输入厂商编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="厂商名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入厂商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="审核状态" clearable>
          <el-option key="0" label="草稿" value="0"/>
          <el-option key="1" label="审核通过" value="1"/>
          <el-option key="2" label="待审核" value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['producer:list:add']"
        >新增</el-button>
      </el-col>-->
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:notice:edit']"
        >修改</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pdrList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="厂商编号" align="center" prop="pkId" width="100" />
      <el-table-column label="厂商名称" align="center" prop="companyName" :show-overflow-tooltip="true"/>
      <el-table-column label="品牌" align="center" prop="brands" width="100">
        <template slot-scope="scope">
<!--          <el-tag size="medium" v-for="(item,index) in scope.row.brands" :key="index" effect="plain"  >{{item.brandName}}</el-tag>-->
          <span style="margin-right: 5px" v-for="(item,index) in scope.row.brands" :key="index">{{item.brandName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="企业法人" align="center" prop="legalPerson" :show-overflow-tooltip="true"/>
      <el-table-column label="业务经理" align="center" prop="bizManagerName" :show-overflow-tooltip="true"/>
      <el-table-column label="联系电话" align="center" prop="contactNo" :show-overflow-tooltip="true"/>
      <el-table-column label="审核状态" align="center" prop="auditStatus" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dictsAuditStatus" :value="scope.row.auditStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" prop="registerTime" width="100"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              type="text"
              size="small"
              icon="el-icon-view"
              @click="handlePreview(scope.row)"
              v-hasPermi="['producer:list:preview']">详情</el-button>
          <el-button v-if="scope.row.auditStatus==2"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleAudit(scope.row)"
              v-hasPermi="['producer:list:audit']"
          >审核</el-button>
          <el-button
                     size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
                     v-hasPermi="['producer:list:edit']"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body center :before-close="handleClose">
      <el-form ref="form" :model="form" :rules="rules"  label-width="100px" :class=" !openIsEdit?'noEidt':'' " v-loading="submitLoading">
        <el-row :gutter="5">
          <el-col :span="12">
            <el-form-item label="企业名称" prop="companyName">
              <el-input v-model="form.companyName" :readonly="!openIsEdit"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业法人" prop="legalPerson">
              <el-input v-model="form.legalPerson" :readonly="!openIsEdit"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="企业地址" prop="address">
              <el-col :span="11">
                <el-cascader style="width: 100%"
                             ref="fromDistrictOptions"
                             v-model="form.districtValues"
                             :options="districtOptions"
                             :disabled="!openIsEdit"
                             clearable filterable
                             @change="handleFromChangeDistrict" placeholder=""
                ></el-cascader>
              </el-col>
              <el-col :span="13"><el-input v-model="form.address" :readonly="!openIsEdit"/></el-col>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="业务经理" prop="bizManagerName">
              <el-input v-model="form.bizManagerName" :readonly="!openIsEdit"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系方式" prop="contactNo">
              <el-input v-model="form.contactNo" :readonly="!openIsEdit"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系邮箱" prop="contactEmail">
              <el-input v-model="form.contactEmail" :readonly="!openIsEdit"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="营业执照号" prop="bizLicenseNo">
              <el-input v-model="form.bizLicenseNo" :readonly="!openIsEdit"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="法人身份证" prop="legalPerIdcdFront">
              <el-image style="width: 100px; height: 100px" fit="contain" :src="form.legalPerIdcdFront" :preview-src-list="[form.legalPerIdcdFront]" v-if="!openIsEdit">
                <div slot="error" class="el-image__error">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
              <el-image style="width: 100px; height: 100px;margin-left: 20px" fit="contain" :src="form.legalPerIdcdBack" :preview-src-list="[form.legalPerIdcdBack]" v-if="!openIsEdit">
                <div slot="error" class="el-image__error">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="营业执照" prop="bizLicense">
              <el-image style="width: 100px; height: 100px" fit="contain" :src="form.bizLicense" :preview-src-list="[form.bizLicense]" v-if="!openIsEdit">
                <div slot="error" class="el-image__error">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
              <el-image style="width: 100px; height: 100px;margin-left: 20px" fit="contain" :src="form.bizLicenseSec" :preview-src-list="[form.bizLicenseSec]" v-if="!openIsEdit">
                <div slot="error" class="el-image__error">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="企业备注" prop="remark">
              <el-input v-model="form.remark" :readonly="!openIsEdit"/>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brands[0].brandName" :readonly="!openIsEdit"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务范围" prop="proj">
              <el-cascader :props="{multiple:true}" style="width:100%"
                           ref="fromProjOptions"
                           v-model="form.projValuesAry"
                           :options="projOptions"
                           :disabled="!openIsEdit"
                           @change="handleChangeProjAry" clearable filterable  placeholder=""></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="openIsEdit" type="primary" @click="onSubmit()">提交</el-button>
        <el-button v-if="isOpenAudit" type="primary" @click="onAudit(form.pkId)">审核通过</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getPdrByPdrId, listPdr, listPdrRelInfo, savePdr, updatePdrByPdrId} from "@/api/producer/pdr.js";
import "@/style/customer.scss";
import {districtOptionSelect} from "@/api/cms/district/district";
import {projOptionsSelect} from "@/api/cms/prod/cate";

export default {
  name: "PdrList",
  data() {
    return {
      submitLoading:false,
      dictsAuditStatus:[
        {
          raw:{
            listClass:"primary",
            cssClass:""
          },
          label:"草稿",
          value:"0"
        },
        {
          raw:{
            listClass:"success",
            cssClass:""
          },
          label:"通过",
          value:"1"
        },
        {
          raw:{
            listClass:"danger",
            cssClass:""
          },
          label:"待审",
          value:"2"
        }
      ],
      districtOptions:[],
      projOptions:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      pdrList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //打开时是否编辑
      openIsEdit:false,
      // 是否打开的是审核弹出层
      isOpenAudit:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyNameComp:"like",
        companyName: undefined,
        pkIdComp:"like",
        pkId: undefined,
        auditStatus: undefined
      },
      // 表单参数
      form: {
        auditStatus:"2",
        brands:[
            {
            brandName:undefined
            }
        ],
        projItems:[],
        districtValues:[],
        projValuesAry:[]
      },
      // 表单校验
      rules: {
        companyName:  [
          {
            validator:(rule, value, callback)=>{
              if(!value){
                callback(new Error("不能为空"))
                this.$notify.error({
                  title: '错误',
                  message: '企业名称不能为空'
                });
              }else{
                callback(); //成功后不传入错误参数即可
              }
            }, trigger: "blur",required:true }
        ],
        legalPerson:  [
          {
            validator:(rule, value, callback)=>{
              if(!value){
                callback(new Error("不能为空"))
                this.$notify.error({
                  title: '错误',
                  message: '企业法人不能为空'
                });
              }else{
                callback(); //成功后不传入错误参数即可
              }
            }, trigger: "blur",required:true }
        ],
        address:  [
          {
            validator:(rule, value, callback)=>{
              if(!value){
                callback(new Error("不能为空"))
                this.$notify.error({
                  title: '错误',
                  message: '企业地址不能为空'
                });
              }else{
                callback(); //成功后不传入错误参数即可
              }
            }, trigger: "blur",required:true }
        ],
        bizManagerName: [
          {
            validator:(rule, value, callback)=>{
              if(!value){
                callback(new Error("不能为空"))
                this.$notify.error({
                  title: '错误',
                  message: '业务经理不能为空'
                });
              }else{
                callback(); //成功后不传入错误参数即可
              }
            }, trigger: "blur",required:true }
        ],
        contactNo: [
          {
            validator:(rule, value, callback)=>{
              if(!value){
                callback(new Error("不能为空"))
                this.$notify.error({
                  title: '错误',
                  message: '联系方式不能为空'
                });
              }else{
                callback(); //成功后不传入错误参数即可
              }
            }, trigger: "blur",required:true }
        ],
        bizLicenseNo: [
          {
            validator:(rule, value, callback)=>{
              if(!value){
                callback(new Error("不能为空"))
                this.$notify.error({
                  title: '错误',
                  message: '营业执照号不能为空'
                });
              }else{
                callback(); //成功后不传入错误参数即可
              }
            }, trigger: "blur",required:true }
        ],
        proj: [
          {
            validator:(rule, value, callback)=>{
              if(!this.form.projValuesAry||this.form.projValuesAry.length<=0){
                callback(new Error("不能为空"))
                this.$notify.error({
                  title: '错误',
                  message: '服务范围不能为空'
                });
              }else{
                callback(); //成功后不传入错误参数即可
              }
            }, trigger: "blur",required:true }
        ],
        /*legalPerIdcdFront: [
          {
            validator:(rule, value, callback)=>{
              if(!value){
                callback(new Error("不能为空"))
                this.$notify.error({
                  title: '错误',
                  message: '法人身份证不能为空'
                });
              }else{
                callback(); //成功后不传入错误参数即可
              }
            }, trigger: "blur",required:true }
        ],
        bizLicense: [
          {
            validator:(rule, value, callback)=>{
              if(!value){
                callback(new Error("不能为空"))
                this.$notify.error({
                  title: '错误',
                  message: '营业执照不能为空'
                });
              }else{
                callback(); //成功后不传入错误参数即可
              }
            }, trigger: "blur",required:true }
        ],*/
      },
    };
  },
  created() {
    this.getList();
    this.getDistrictOptions();
    this.getProjOptions();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listPdrRelInfo(this.queryParams).then(response => {
        this.pdrList = response.data;
        this.total = Number(response.total);
        this.loading = false;
      });
    },
    getDistrictOptions(){
      districtOptionSelect().then( response => {
        this.districtOptions = response;
      });
    },
    getProjOptions(){
      projOptionsSelect().then(data => {
        this.projOptions = data
      });
    },

    onAudit(pdrId){
      this.$confirm('确认审核通过吗？'+pdrId)
          .then(_ => {
            let data={"pkId":pdrId,"auditStatus":"1"}
            updatePdrByPdrId(data).then(response => {
              this.$alert("操作成功");
              this.handleClose();
              this.handleQuery();
            });

          })
          .catch(_ => {});
    },
    onSubmit(){
      this.$confirm('确认提交吗？').then(_ => {
        this.$refs["form"].validate( valid => {
          if (!valid){
            return;
          }

          this.submitLoading=true;
          savePdr(this.form).then(response => {
            this.$alert("操作成功");
            this.handleClose();
            this.handleQuery();
          }).finally(()=>{
            this.submitLoading=false;
          });

        })

      }).catch(_ => {});
    },

    // 取消按钮
    handleClose() {
      this.open = false;
      this.isOpenAudit=false;
      this.openIsEdit=false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        auditStatus:"2",
        brands:[
          {
            brandName:undefined
          }
        ],
        projItems:[],
        districtValues:[],
        projValuesAry:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleFromChangeDistrict(value){
      if(value){
        this.form.provinceCode=value[0]
        this.form.cityCode=value[1]
        this.form.districtCode=value[2]

        //通过搜索 选择 此处获取不到值
        //let arr = this.$refs['fromDistrictOptions'].getCheckedNodes()[0].pathLabels
        //let nodesInfo = this.$refs['fromDistrictOptions'].getCheckedNodes();

        //当使用getCheckedNodes()方法获取不到节点时,我们可以使用反查的方法getNodeByValue(),去找当前节点
        let nodesInfo=this.$refs[`fromDistrictOptions`].panel.getNodeByValue(value)
        let lableArr=nodesInfo.pathLabels;
        this.form.province=lableArr[0]?lableArr[0]:undefined;
        this.form.city=lableArr[1]?lableArr[1]:undefined;
        this.form.district=lableArr[2]?lableArr[2]:undefined;

        //此方法也可以
        /*this.$nextTick(() => {
          let arrLabel = this.$refs["fromDistrictOptions"].presentText.split(
              this.$refs["fromDistrictOptions"].separator
          );

          this.form.province=arrLabel[0]
          this.form.city=arrLabel[1]
          this.form.district=arrLabel[2]
        });*/

      }
    },
    handleChangeProjAry(value){
      this.form.projItems=[];
      for(let inx in value){
        let node=this.$refs[`fromProjOptions`].panel.getNodeByValue(value[inx])
        if(!node.isLeaf){//是否叶子节点
          continue;
        }

        let codeArr=node.path;
        let lableArr=node.pathLabels;

        let projCode=codeArr[0]
        let projName=lableArr[0]
        let cateCode=codeArr[1]
        let cateName=lableArr[1]
        let itemCode=codeArr[2]
        let itemName=lableArr[2]
        let object ={
          projCode:projCode,
          projName:projName,
          cateCode:cateCode,
          cateName:cateName,
          itemCode:itemCode,
          itemName:itemName
        }
        this.form.projItems.push(object)
     }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.noticeId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.openIsEdit=true;
      this.title = "新增";
    },

    /**
     * 厂商详情按钮
     * @param row
     */
    handlePreview(row){
      const pkId=row.pkId;
      console.log("====",pkId);
      let query={"producerId":pkId};
      return getPdrByPdrId(query).then(response => {
        this.form = response.data;
        if(!this.form.districtCode){
          this.form.districtValues=[this.form.provinceCode,this.form.cityCode];
        }else{
          this.form.districtValues=[this.form.provinceCode,this.form.cityCode,this.form.districtCode];
        }

        if(!this.form.brands || this.form.brands.length<=0){
          this.form.brands=[{brandName: undefined}];//初始化
        }
        if(!!this.form.projItems && this.form.projItems.length>0){
          this.form.projValuesAry=[];
          let projs=this.form.projItems;
          for(let index in projs){
            let ary=[];
            ary.push(projs[index].projCode);
            ary.push(projs[index].cateCode);
            ary.push(projs[index].itemCode);
            this.form.projValuesAry.push(ary)
          }
        }

        this.open = true;
        this.openIsEdit=false;
        this.title = "厂商信息";
      });
    },

    handleUpdate(row){
      this.handlePreview(row).then(()=>{
        this.openIsEdit=true;
      })

    },

    /**
     * 厂商审核
     * @param row
     */
    handleAudit(row){
      this.isOpenAudit=true;
      this.handlePreview(row);
    },
  }
};
</script>
